package com.demo.service.impl;

import com.demo.dto.DictDTO;
import com.demo.entity.SysDict;
import com.demo.mapper.SysDictMapper;
import com.demo.service.SysDictService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysDictServiceImpl implements SysDictService {
    @Autowired
    private SysDictMapper dictMapper;

    @Override
    @CacheEvict(cacheNames = {"groupDict"})
    public int add(SysDict dict) {
        return dictMapper.add(dict);
    }

    @Override
    @CacheEvict(cacheNames = {"groupDict"})
    public int remove(int id) {
        return dictMapper.delete(id);
    }


    @Override
    public PageInfo<SysDict> findAll(int pageIndex, int pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        PageInfo<SysDict> pageInfo = new PageInfo<>(dictMapper.findAll());
        return pageInfo;
    }

    @Override
    public List<SysDict> find() {
        return dictMapper.findAll();
    }

    @Override
    public List<String> listMap() {
        return dictMapper.listMap();
    }

    @Override
    public PageInfo<SysDict> findByGroup(String group, int pageIndex, int pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        PageInfo<SysDict> pageInfo = new PageInfo<>(dictMapper.findByGroup(group));
        return pageInfo;
    }


    @Override
    public SysDict get(int id) {
        return dictMapper.get(id);
    }

    @Override
    public List<DictDTO> findGroup() {
        return dictMapper.findGroup();
    }

    @Override
    @CacheEvict(cacheNames = {"groupDict"})
    public int update(SysDict dict) {
        return dictMapper.update(dict);
    }

    @Override
    public String groupKey(String groupName) {
        return dictMapper.groupKey(groupName);
    }

    @Override
    public List<SysDict> findByGroupName(String group) {
        return dictMapper.findByGroup(group);
    }

    @Cacheable(cacheNames = {"groupDict"})
    @Override
    public Map<String, List<SysDict>> findDictMap() {
        List<SysDict> list = dictMapper.findAll();
        Map<String, List<SysDict>> map = new HashMap<>();
        for (SysDict dict : list) {
            List<SysDict> groupDict = map.get(dict.getGroupKey());
            if (groupDict == null) {
                groupDict = new ArrayList<>();
                map.put(dict.getGroupKey(), groupDict);
            }
            groupDict.add(dict);
        }
        return map;
    }
}
